const form = document.querySelector('form')
const nameInp = document.querySelector('.username')
const pwdInp = document.querySelector('.password')
const errBox = document.querySelectorAll('.error')
// console.log(form,nameInp,pwdInp,errBox)

form.addEventListener('submit', e => {
    e.preventDefault()
    const name = nameInp.value
    const pwd = pwdInp.value
    console.log(name,pwd)
    if (!name || !pwd) return alert('请输入用户名和密码')
    const xhr = new XMLHttpRequest()

    xhr.open('POST', 'http://localhost:8888/users/login')
    xhr.onload = function () {

        const res = JSON.parse(xhr.responseText)
        console.log(res)
        if (res.code === 0) {
            for (var i = 0; i < errBox.length; i++) {
                errBox[i].style.display = "block";
            }
            return
        }
        window.localStorage.setItem('id', res.user.id)

        window.localStorage.setItem('token', res.token)

        window.location.href = '../views/index.html'
    }
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    xhr.send(`username=${name}&password=${pwd}`)
})